package common.controls.utils
{
	
	/**  
	 * 
	 * @author carrey
	 * */ 
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.InteractiveObject;
	import flash.display.LineScaleMode;
	import flash.display.Sprite;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	public class DragController extends EventDispatcher
	{
		private var _target:DisplayObjectContainer;
		private var _dragArea:InteractiveObject;
		private var _rect:Rectangle;
		
		private var rectArea:Sprite;
		
		public function DragController( target:DisplayObjectContainer, dragArea:InteractiveObject, rect:Rectangle=null )
		{
			this._target = target;
			this._dragArea = dragArea;
			this._rect = rect;
			
			init();
		}
		
		private function init():void
		{
			if( null==_rect )
			{
				_rect = _target.getBounds( _target );
			}
			rectArea = new Sprite();
			rectArea.graphics.beginFill( 0,0 );
			rectArea.graphics.lineStyle( 1, 0, 1, false, LineScaleMode.NONE );
			rectArea.graphics.drawRect( _rect.x, _rect.y, _rect.width, _rect.height );
			
			_dragArea.addEventListener( MouseEvent.MOUSE_DOWN, onMousedown, false, 0, true );
		}
		
		public function dragAreaSizeChange():void
		{
			_rect = _target.getBounds( _target );
			rectArea.graphics.clear();
			rectArea.graphics.beginFill( 0,0 );
			rectArea.graphics.lineStyle( 1, 0, 1, false, LineScaleMode.NONE );
			rectArea.graphics.drawRect( _rect.x, _rect.y, _rect.width, _rect.height );
		}
		
		public function destroy():void
		{
			_dragArea.removeEventListener( MouseEvent.MOUSE_DOWN, onMousedown );
			_target = null;
			_dragArea = null;
			_rect = null;
			rectArea = null;
		}
		
		private var isMousedown:Boolean = false;
		private function onMousedown( e:MouseEvent ):void
		{
			if( false==isMousedown )
			{
				_target.addChild( rectArea );
				rectArea.x = 0;
				rectArea.y = 0;
				rectArea.startDrag();
				rectArea.alpha = 0;
				rectArea.stage.addEventListener( MouseEvent.MOUSE_MOVE, onMouseMove, false, 0, true );
				rectArea.stage.addEventListener( MouseEvent.MOUSE_UP, onMouseup, false, 0, true );
				isMousedown = true;
			}
		}
		
		private function onMouseMove( e:MouseEvent ):void
		{
			(e.currentTarget as InteractiveObject).removeEventListener( MouseEvent.MOUSE_MOVE, onMouseMove );
			rectArea.alpha = 1;
		}
		
		private function onMouseup( e:MouseEvent ):void
		{
			rectArea.stage.removeEventListener( MouseEvent.MOUSE_UP, onMouseup );
			_target.removeChild( rectArea );
			
			rectArea.stopDrag();
			_target.x = int(rectArea.x + _target.x);
			_target.y = int(rectArea.y + _target.y);
			isMousedown = false;
		}
	}
}













